//
//  ASRManager_KDXF.m
//  ASR_Demo
//
//  Created by marco on 16/3/11.
//  Copyright © 2016年 Marco. All rights reserved.
//

#import "ASRManager_KDXF.h"
#import <iflyMSC/iflyMSC.h>
#import "ISRDataHelper.h"
#import "Recorder.h"
#import "IATConfig.h"

static NSString * _cloudGrammerid =nil;//在线语法grammerID



@interface ASRManager_KDXF () <IFlySpeechRecognizerDelegate>

@property (nonatomic,strong) IFlySpeechRecognizer* iFlySpeechRecognizer;
@property (nonatomic,strong) NSMutableString *curResult;
@property (nonatomic, strong) NSString *pcmFilePath;//音频文件路径
@property (nonatomic,assign) ASRSystemType asrSystemType;
@property (nonatomic,assign) BOOL isStart;
@end

@implementation ASRManager_KDXF


+(instancetype) sharedManager
{
    static ASRManager_KDXF* instance = nil;
    //    dispatch_once_t token;
    //    dispatch_once(&token, ^{
    //        instance = [ASRManager new];
    //    });
    if( !instance )
    {
        instance = [self new];
        
    }
    return instance;
}
- (instancetype)init
{
    self = [super init];
    if (self)
    {
        [IFlySetting showLogcat:NO];

        NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",@"56e13b31"];
        [IFlySpeechUtility createUtility:initString];
     
        
        if( !_iFlySpeechRecognizer )
        {
            _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance]; //设置听写模式
        }
        //demo录音文件保存路径
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *cachePath = [paths objectAtIndex:0];
        _pcmFilePath = [[NSString alloc] initWithFormat:@"%@",[cachePath stringByAppendingPathComponent:@"asr.pcm"]];
        _isStart = NO;

    }
    return self;
}

- (int) realtimeRecog:(NSData*)pData type:(ASRSystemType)pType
{

    return 0;
}

- (int) openSystem:(ASRSystemType)pType samplingRate:(NSString*)pSamplingRate
{
    _isStart = YES;
    _asrSystemType = pType;
    
    _curResult = [NSMutableString new];
    
    IATConfig *instance = [IATConfig sharedInstance];
    
    [_iFlySpeechRecognizer cancel];

    
    if( pType == kASRSystemType_ZH )
    {
        instance.accent = [IATConfig mandarin];
    }
    else if( pType == kASRSystemType_UYGHUR )
    {
        instance.accent = [IATConfig uyghur];
    }
    
    if( pSamplingRate == g_kASRSampleRateRate_8kb )
    {
        instance.sampleRate = @"8000";
    }
    else if( pSamplingRate == g_kASRSampleRateRate_16kb )
    {
        instance.sampleRate = @"16000";
    }
    

    _iFlySpeechRecognizer.delegate = self;
    [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
    [_iFlySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
    //设置最长录音时间
    [_iFlySpeechRecognizer setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
    //设置后端点
    [_iFlySpeechRecognizer setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
    //设置前端点
    [_iFlySpeechRecognizer setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
    //网络等待时间
    [_iFlySpeechRecognizer setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
    
    //设置采样率，推荐使用16K
    [_iFlySpeechRecognizer setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
    
    if ([instance.language isEqualToString:[IATConfig chinese]]) {
        //设置语言
        [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
        //设置方言
        [_iFlySpeechRecognizer setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
    }else if ([instance.language isEqualToString:[IATConfig english]]) {
        [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
    }
    //设置是否返回标点符号
    [_iFlySpeechRecognizer setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];
    //设置音频来源为麦克风
    [_iFlySpeechRecognizer setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
    
    //设置听写结果格式为json
    [_iFlySpeechRecognizer setParameter:@"json" forKey:[IFlySpeechConstant RESULT_TYPE]];
    
    //保存录音文件，保存在sdk工作路径中，如未设置工作路径，则默认保存在library/cache下
    [_iFlySpeechRecognizer setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];

    
    
    [_iFlySpeechRecognizer startListening];
    return 0;
}
- (void)closeSystem
{
    [_iFlySpeechRecognizer stopListening];
    [_iFlySpeechRecognizer cancel];
    _isStart = NO;
}

#pragma mark IFlySpeechRecognizerDelegate

- (void) onError:(IFlySpeechError *) errorCode
{
//    NSLog(@"%@",errorCode.errorDesc);
}

- (void) onResults:(NSArray *) results isLast:(BOOL)isLast
{
    NSMutableString *resultString = [[NSMutableString alloc] init];
    NSDictionary *dic = results[0];
    for (NSString *key in dic) {
        [resultString appendFormat:@"%@",key];
    }
    NSString * resultFromJson =  [ISRDataHelper stringFromJson:resultString];
    [_curResult appendString:resultFromJson];

    if (isLast){

        if( _asrSystemType == kASRSystemType_ZH )
        {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:g_kASRComplete_ZH object:_curResult];
        }
        else if( _asrSystemType == kASRSystemType_UYGHUR )
        {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:g_kASRComplete_UYGHUR object:_curResult];
        }
        _curResult = [NSMutableString new];
        if( _isStart )
        {
            [_iFlySpeechRecognizer startListening];
        }
    }

}



@end
